from django.db import models

from markdownx.models import MarkdownxField
from markdownx.utils import markdownify


class CourseManager(models.Manager):

    def valid_courses(self):
        return Course.objects.filter(visible=True)


class Course(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=40)
    semester = models.CharField(max_length=50, )
    classroom = models.CharField(max_length=50, )
    course_teach_url = models.CharField(max_length=300)
    course_zone = models.CharField(verbose_name='Zoom id', max_length=200)
    overview = models.TextField(blank=True)
    visible = models.BooleanField(default=True)

    objects = CourseManager()

    def __str__(self):
        return '%s %s %s' % (self.title, self.semester, self.classroom)

    @property
    def full_name(self):
        "Returns the course's full name."
        return '%s%s%s' % (self.title, self.semester, self.classroom)

    class Meta:
        ordering = ['title', 'semester', 'classroom']


class Lecture(models.Model):
    course = models.ForeignKey(Course, related_name='lectures')
    title = models.CharField(max_length=200)
    start = models.DateTimeField()
    end = models.DateTimeField()

    notes = MarkdownxField()

    @property
    def formatted_markdown(self):
        return markdownify(self.notes)

    def __str__(self):
        return '{} {}'.format(self.title, self.start)

    def to_obj(self):
        obj = {}
        obj['id'] = self.pk
        obj['title'] = self.title
        obj['start'] = int(self.start.timestamp() * 1e3)
        obj['end'] = int(self.end.timestamp() * 1e3)
        obj['zone'] = self.course.course_zone
        return obj
